﻿/// <reference path="../Core.js" />
IM.FriendManager = function() {
    IM.Base.apply(this, arguments);
    this.FriendList;
    this.Friends = null; //
    this.GetFriendListCallBack = function(data, obj) {//obj为当前friendManager对象
        if (data.Result) {
            //检查是否已经加载过好友，没有的话直接将新好友列表存入this.Friends
            if (obj.Friends != null) {

                for (var i = 0; i < data.Friends.length; i++) {
                    var friend = obj.FindFriendById(data.Friends[i].UserId);
                    if (friend != null) {//如果this.Friends中存在该好友，将新信息存入该好友
                        for (var key in data.Friends[i]) {
                            friend[key] = data.Friends[i][key]; //将好友新信息copy到当前好友中
                        }
                    }
                    else {//如果不存在，直接将该好友存入this.Friends集合
                        obj.Friends.Add(data.Friends[i]);
                    }
                }
            }
            else {
                obj.Friends = new IM.Utility.ArrayList();
                obj.Friends.Items = data.Friends;
            }
            obj.RefreshUI();
        }
    };

    this.RefreshUI = function() {
        this.FriendList = new IM.Control.FriendList({ Render: "friendListDiv" });
        this.FriendList.DataSource = this.Friends;
        this.FriendList.DataBind();
        this.FriendList.Show();

    };

    this.GetFriendList = function() {//获取好友列表
        $.post("GetFriendList", null, (function(obj) { return function(data) { obj.GetFriendListCallBack(data, obj) }; })(this), "json");
    };

    //按用户编号查询当前好友列表中的用户
    this.FindFriendById = function(Userid) {
        var friend = null;
        if (this.Friends != null) {
            for (var i = 0; i < this.Friends.Count(); i++) {
                var f = this.Friends.Find(i);
                if (f.UserId == Userid) {
                    friend = f;
                    break;
                }
            }
        }
        return friend;
    };

    //开始定时取好友IM.Chat.FriendManager.GetFriendList
    this.StartInterval = function() {
        this.GetFriendList(); //先取一次好友信息
        IM.SetInterval(11000, 0, (function(obj) { return function() { obj.GetFriendList(); }; })(this));
    };
};